import { constantRoutes } from '@/router'
import { getRoutes } from '@/api/basics/role'
import Layout from '@/layout'

/**
 * 判断路由权限
 * @param {Array} roles 用户权限
 * @param {Object} route 路由对象
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * 配置转路由组件
 * @param {Array} routes 路由配置
 * @param {Array} roles 用户权限
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      tmp.component = tmp.component === 'Layout' ? Layout : loadView(tmp.component)
      if (tmp.children && tmp.children.length) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })
  return res
}

/**
 * 路由懒加载
 * return () => import(`@/views/${view}`) // babel-eslint需降至 @7.2.3 ｜ use require
 * bug in https://github.com/babel/babel/issues/13060
 * @param {String} view
 * @return {String}
 */
export const loadView = (view) => {
  return (resolve) => require([`@/views/${view}`], resolve)
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = routes
  }
}

const actions = {
  // 生成完整路由
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      getRoutes().then(response => {
        const { data } = response
        // 过滤本地路由
        const _constantRoutes = filterAsyncRoutes(constantRoutes, roles)
        const accessedRoutes = filterAsyncRoutes(data, roles)
        accessedRoutes.push({ path: '*', redirect: '/404', hidden: true })
        const resRoutes = _constantRoutes.concat(accessedRoutes)
        commit('SET_ROUTES', resRoutes, roles)
        resolve(resRoutes)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
